<template>
  <div class="card">
    <customer-tag-notice :customerTagArr="customerTagArr"></customer-tag-notice>
    <headcom v-if="JSON.stringify(jsondata.headinfo) !== '{}'" :jsondata="jsondata" :cardid="cardid"></headcom>
    <van-popup v-model="showReview" round position="bottom" :close-on-click-overlay="false">
      <van-field label="评论" disabled="disabled" />
      <van-field v-model="myreview" rows="10" autosize type="textarea" maxlength="1000" placeholder="请写评论"
        show-word-limit />
      <div style="text-align: center; margin: auto">
        <van-button plain type="info" style="width: 50%" @click="saveReview()">确定</van-button>
        <van-button plain type="info" style="width: 50%" @click="cancelReview()">取消</van-button>
      </div>
    </van-popup>
    <div style="margin-bottom: 10vh">
      <van-notice-bar @click="toggleExpand" v-if="
        notice !== '' &&
        notice.contents !== '' &&
        notice.contents.length > 0 &&
        !isExpanded
      " left-icon="volume-o" :scrollable="true" :text="notice.contents.join(';')">
      </van-notice-bar>
      <van-notice-bar v-show="isExpanded" :wrapable="true" @click="toggleExpand"
        :class="{ 'expanded-notice': true, 'multi-line-notice': true }" v-if="
          notice !== '' && notice.contents !== '' && notice.contents.length > 0
        " left-icon="volume-o" :scrollable="false">
        <div v-for="(i, index) in notice.contents" style="padding: 5px">
          {{ `${index + 1}.${i}` }}
        </div>
      </van-notice-bar>
      <van-tabs @click="openRel" v-model="tabpage" sticky swipe-threshold="4">
        <van-tab title="动态" name="dynamic" v-if="hasDynamic">
          <dynamic :bo="idobject" :id="cardid"></dynamic>
        </van-tab>
        <van-tab title="场景" name="scenario" v-if="jsondata.scenario"><!-- title之后换成场景名, if中判断有无场景 -->
          <scenario :idobject="idobject" :cardid="cardid" :isqd="isqd" :key="scenarioKey"
            :jsondataDetails="jsondata.Details"></scenario>
        </van-tab>
        <van-tab title="详情" name="maininfo">
          <div style="background: #fff; padding: 10px 0px; box-sizing: border-box">
            <van-collapse v-model="activeNames" accordion>
              <v-views ref="vViews1"></v-views>
              <div v-if="idobject == 'jykf'">
                <div style="height: 40wh">
                  <mytimeline :data="jykfMap" @refresh="fetchData"></mytimeline>
                </div>
              </div>
              <van-collapse-item v-for="item in jsondata.Details" :key="item.groupStitle" :title="item.groupStitle">
                <div v-for="fieldvalue in item.groupvalue" :key="fieldvalue.id">
                  <template v-if="fieldvalue.lCanOutput == '0'"> </template>
                  <template v-else-if="fieldvalue.sUIType == 'file'">
                    <div style="
                        color: #323233;
                        font-size: 14px;
                        line-height: 24px;
                        padding: 5px;
                      " :class="{ field_prompt: fieldvalue.snote }">
                      <span class="custom-title">{{ fieldvalue.sTitle }}</span>
                      <van-icon v-if="fieldvalue.snote && fieldvalue.snote !== ''" name="info-o"
                        @click="iconClick(fieldvalue.snote)" />
                    </div>
                    <a v-for="filevalue in fieldvalue.valuelist" :key="filevalue.url" :href="filevalue.url">{{
                      filevalue.file.name }}</a>
                  </template>

                  <!--                <template v-if="fieldvalue.sUIType == 'file'">-->
                  <!--                  <div style="color:#323233;font-size:14px;line-height:24px;padding:5px;">{{ fieldvalue.sTitle }}</div>-->
                  <!--                  <div>-->
                  <!--                    <van-button style="margin:3px" round type="info" v-for="filevalue in fieldvalue.valuelist" :key="filevalue.url" href="" @click.prevent="showFile(filevalue, '1')">{{ filevalue.file.name }}</van-button>-->
                  <!--                  </div>-->

                  <!--                </template>-->
                  <template v-else-if="fieldvalue.sUIType == 'picture'">
                    <div style="
                        color: #323233;
                        font-size: 14px;
                        line-height: 24px;
                        padding: 5px;
                      ">
                      <span class="custom-title">{{ fieldvalue.sTitle }}</span>
                      <van-icon v-if="fieldvalue.snote && fieldvalue.snote !== ''" name="info-o"
                        @click="iconClick(fieldvalue.snote)" />
                    </div>
                    <van-uploader v-model="fieldvalue.valuelist" disabled max-count="0" :deletable="false">
                    </van-uploader>
                  </template>
                  <template v-else-if="
                    fieldvalue.sUIType == 'string' &&
                    fieldvalue.sFormat == 'star'
                  ">
                    <van-row type="flex" align="center" justify="space-between" style="margin-top: 10px">
                      <van-col style="font-size: 16px; margin-left: 16px">{{
                        fieldvalue.sTitle
                      }}</van-col>
                      <van-col>
                        <van-rate v-model="fieldvalue.value" :size="25" color="#ffd21e" void-icon="star"
                          void-color="#eee" readonly />
                      </van-col>
                    </van-row>
                    <!-- <van-cell :title="fieldvalue.sTitle">
                    <template #title>
                      <span class="custom-title">{{fieldvalue.sTitle}}</span>
                      <van-icon v-if="fieldvalue.snote && fieldvalue.snote !== ''" name="info-o"  @click="iconClick(fieldvalue.snote)" />
                    </template>
<template #default>
                      <van-rate v-model="fieldvalue.value" :size="25" color="#ffd21e" void-icon="star" void-color="#eee" readonly />
                    </template>
</van-cell> -->
                  </template>
                  <template v-else-if="fieldvalue.sUIType == 'extract'">
                    <van-cell :title="fieldvalue.sTitle" :value="fieldvalue.value"
                      @click="targetList(fieldvalue)"></van-cell>
                  </template>
                  <template v-else>
                    <van-cell class="cellvalue1" :title="fieldvalue.sTitle">
                      <template #title>
                        <span class="custom-title">{{
                          fieldvalue.sTitle
                        }}</span>
                        <van-icon v-if="fieldvalue.snote && fieldvalue.snote !== ''" name="info-o"
                          @click="iconClick(fieldvalue.snote)" />
                      </template>
                      <template #default>
                        <span :style="{
                          color: fieldvalue?.sFormat.split(';').filter(i => {
                            return i == 'fontcolor:red'
                          })[0]?.split(':')[1]
                        }" class="valueleft" v-html="fieldvalue.value"></span>
                        <!-- <template v-if="isEditField(fieldvalue)">
                        <template  v-if="updatemsg.id != fieldvalue.ID">
                          <span class="valueleft" v-html="fieldvalue.value"></span>
                          <van-icon name="edit" size="1rem" @click="auditEdit(fieldvalue)"/>
                        </template>
<template v-if="updateshow && updatemsg.id == fieldvalue.ID">
                          <input v-model="fieldvalue.updatevalue" >
                          <van-icon name="certificate" size="1.2rem" @click="auditEditSave(fieldvalue)" />
                          <van-icon name="cross" size="1.2rem" @click="auditEditCancel(fieldvalue)"/>
                        </template>
</template>
<template v-else>
                        <span class="valueleft" v-html="fieldvalue.value"></span>
                      </template> -->
                      </template>
                    </van-cell>
                  </template>
                </div>
                <br />
              </van-collapse-item>
            </van-collapse>
            <van-tabbar v-model="active" safe-area-inset-bottom>
              <!--
            <template v-if="this.$route.query.idobject !== 'currentstock'">
              <van-tabbar-item v-for="item in jsondata.operation" :key="item.id" @click="excuteFunc(item)">{{ item.title }}</van-tabbar-item>
            </template>
            <van-tabbar-item v-if="['dailyreports', 'weekreports', 'monthreport1', 'yzlh2', 'pxjlb', 'activity', 'campaign', 'activitycust', 'activitybiz'].indexOf(this.$route.query.idobject) >= 0" @click="review()">点评</van-tabbar-item>
            <van-tabbar-item v-if="this.$route.query.idobject === 'dailyreports'" @click="showPath()">轨迹</van-tabbar-item>
            -->
              <van-tabbar-item :key="index" v-for="(button, index) in visibleButtons" @click="excuteFunc(button)">
                {{ button.title }}
              </van-tabbar-item>
              <!-- <van-button-->
              <!--              v-for="(button, index) in visibleButtons"-->
              <!--              :key="button.id"-->
              <!--              type="primary"-->
              <!--              size="small"-->
              <!--              class="button"-->
              <!--              @click="button.action"-->
              <!--            >-->
              <!--              {{ button.title }}-->
              <!--            </van-button> -->
              <van-tabbar-item style="line-height: 50px" v-if="hiddenButtons && hiddenButtons.length > 0"
                @click="showMoreActionSheet = true">
                <template #icon="props">
                  <div style="margin-top: 5px">
                    <van-icon name="more-o" color="#646566"></van-icon>
                  </div>
                </template>
              </van-tabbar-item>
            </van-tabbar>
          </div>
        </van-tab>

        <van-tab v-for="rel in jsondata.relevant" :key="rel.ui_key" :title="rel.title" :name="rel.ui_key">
          <van-list v-model="loading" :finished="finished" finished-text="已加载全部数据" @load="onLoad(rel)">
            <template v-if="
              false &&
              (rel.current_object === 'bfpj' ||
                rel.current_object === 'hdpj') &&
              bfpjdata.Details !== undefined
            ">
              <div>
                <v-views ref="vViews2"></v-views>
                <div v-for="fieldvalue in bfpjdata.Details[0].groupvalue" :key="fieldvalue.id">
                  <!--                  <template v-if="fieldvalue.sUIType == 'file'">-->
                  <!--                    <div style="color:#323233;font-size:14px;line-height:24px;padding:5px;">{{fieldvalue.sTitle}}</div>-->
                  <!--                    <a v-for="filevalue in fieldvalue.valuelist" :key="filevalue.url" :href="filevalue.url">{{filevalue.file.name}}</a>-->
                  <!--                  </template>-->

                  <template v-if="fieldvalue.sUIType == 'file'">
                    <div style="
                        color: #323233;
                        font-size: 14px;
                        line-height: 24px;
                        padding: 5px;
                      ">
                      {{ fieldvalue.sTitle }}
                    </div>
                    <div>
                      <van-button style="margin: 3px" round type="info" v-for="filevalue in fieldvalue.valuelist"
                        :key="filevalue.url" href="" @click.prevent="showFile(filevalue, '2')">{{ filevalue.file.name
                        }}</van-button>
                    </div>
                  </template>
                  <template v-else-if="fieldvalue.sUIType == 'picture'">
                    <div style="
                        color: #323233;
                        font-size: 14px;
                        line-height: 24px;
                        padding: 5px;
                      ">
                      {{ fieldvalue.sTitle }}
                    </div>
                    <van-uploader v-model="fieldvalue.valuelist" disabled :deletable="false">
                    </van-uploader>
                  </template>
                  <template v-else-if="fieldvalue.sUIType == 'extract'">
                    <van-cell :title="fieldvalue.sTitle" :value="fieldvalue.value"
                      @click="targetList(fieldvalue)"></van-cell>
                  </template>
                  <template v-else-if="
                    fieldvalue.sUIType == 'string' &&
                    fieldvalue.sFormat == 'star'
                  ">
                    <van-cell :title="fieldvalue.sTitle">
                      <template #default>
                        <van-rate v-model="fieldvalue.value" :size="25" color="#ffd21e" void-icon="star"
                          void-color="#eee" readonly />
                      </template>
                    </van-cell>
                  </template>
                  <template v-else>
                    <van-cell :title="fieldvalue.sTitle">
                      <template #default>
                        <span class="valueleft" v-html="fieldvalue.value" :id="fieldvalue.sField"></span>
                      </template>
                    </van-cell>
                  </template>
                </div>
                <van-tabbar v-model="active1" safe-area-inset-bottom>
                  <van-tabbar-item v-for="item1 in bfpjdata.operation" :key="item1.id"
                    @click="excuteFunc1(item1, rel.current_object)">{{ item1.title }}</van-tabbar-item>
                </van-tabbar>
              </div>
            </template>
            <template v-else>
              <div v-for="item in rellist" :key="item.id">
                <template v-if="item.sUIType == 'file'">
                  <div style="
                      color: #323233;
                      font-size: 14px;
                      line-height: 24px;
                      padding: 5px;
                    ">
                    {{ item.title }}
                  </div>
                  <a v-for="filevalue in fieldvalue.valuelist" :key="filevalue.url" :href="filevalue.url">{{
                    filevalue.file.name }}</a>
                </template>

                <!--                <template v-if="item.sUIType == 'file'">-->
                <!--                  <div style="color:#323233;font-size:14px;line-height:24px;padding:5px;">{{ item.title }}</div>-->
                <!--                  <div>-->
                <!--                    <van-button style="margin:3px" round type="info" v-for="filevalue in fieldvalue.valuelist" :key="filevalue.url" href="" @click.prevent="showFile(filevalue, '2')">{{ filevalue.file.name }}</van-button>-->
                <!--                  </div>-->
                <!--                </template>-->
                <template v-else-if="item.sUIType == 'picture'">
                  <div style="
                      color: #323233;
                      font-size: 14px;
                      line-height: 24px;
                      padding: 5px;
                    ">
                    {{ item.title }}
                  </div>
                  <van-uploader v-model="fieldvalue.valuelist" disabled :deletable="false" accept="image/*"
                    :name="filevalue.sField">
                  </van-uploader>
                </template>

                <template v-else-if="
                  rel.current_object == 'flowclmx' ||
                  rel.current_object == 'flowrecord'
                ">
                  <van-cell>
                    <template #title>
                      <div v-html="item.title"></div>
                      <span style="font-size: 12px; color: #969799" v-html="item.label"></span>
                    </template>
                    <template #default>
                      <div style="padding-left: 0px" v-html="item.value"></div>
                    </template>
                  </van-cell>
                </template>

                <template v-else>
                  <van-cell @click="openRelCard(rel, item)">
                    <template #title>
                      <div v-html="item.title"></div>
                      <span style="font-size: 12px; color: #969799" v-html="item.label"></span>
                    </template>
                    <template #default>
                      <div style="padding-left: 0px" v-html="item.value"></div>
                      <img v-if="item[rel.current_object + '_sfzdys'] == '1'" src="@/assets/img_important2.png" style="
                          width: 40px;
                          position: absolute;
                          right: 0;
                          bottom: 0;
                        " />
                    </template>
                  </van-cell>
                </template>
              </div>
            </template>
          </van-list>

          <van-button v-if="
            rel.cannew === '1' &&
            bfpjdata.Details == undefined &&
            rel.current_object != 'dp' &&
            rel.current_object != 'yidu'
          " style="
              position: fixed;
              border-radius: 10px;
              right: 10vw;
              bottom: 10vh;
            " type="info" @click="addRel(rel)">新增</van-button>
        </van-tab>

        <van-tabbar v-if="relBusinessVisibleMenuButtons.length > 0" v-model="active" safe-area-inset-bottom>
          <van-tabbar-item :key="index" v-for="(button, index) in relBusinessVisibleMenuButtons"
            @click="handleMenusClick(button)">
            {{ button.title }}
          </van-tabbar-item>

          <van-tabbar-item style="line-height: 50px" v-if="relBusinessHiddenMenuButtons.length > 0"
            @click="showRelHiddenMenuActionSheet = true">
            <template #icon="props">
              <div style="margin-top: 5px">
                <van-icon name="more-o" color="#646566"></van-icon>
              </div>
            </template>
          </van-tabbar-item>
        </van-tabbar>
      </van-tabs>
    </div>

    <!-- ActionSheet 组件 -->
    <van-action-sheet v-model="showMoreActionSheet" :actions="hiddenButtons" @select="onSelect" />
    <van-action-sheet round v-model="showRelHiddenMenuActionSheet" :actions="relBusinessHiddenMenuActions"
      @select="handleMenusSelect" close-on-click-action />

    <van-popup v-model="showBusinessPopup" round position="bottom" :style="{ height: '100%' }">
      <component v-if="showBusinessPopup" :businessName="currentBusinessName" :is="currentBusinessComponent"
        :handleBusinesSubmit="handleBusinesSubmit" :handleBusinessCancle="handleBusinessCancle"
        :idobject="currentBusinessObject" :headObject="$route.query.idobject" :headObjectId="$route.query.itemid">
      </component>
    </van-popup>

    <van-popup v-model="relcardshow" position="right" closeable style="width: 80vw">
      <div style="padding-top: 5vh">
        <van-collapse v-model="relactiveNames">
          <van-collapse-item v-for="item in reldata.Details" :key="item.groupStitle" :name="item.groupStitle"
            :title="item.groupStitle">
            <van-cell v-for="fieldvalue in item.groupvalue" :key="fieldvalue.id" :title="fieldvalue.sTitle"
              :value="fieldvalue.value"></van-cell>
          </van-collapse-item>
        </van-collapse>
      </div>
    </van-popup>
    <!-- <van-popup v-model="updateshow"   position="top" :style="{ height: '30%' }">
      <div>
        <van-form >
          <van-field :label="updatemsg.sTitle" :name="updatemsg.sField" :placeholder="updatemsg.sTitle"></van-field>
        </van-form>
        <van-tabbar>
          <van-tabbar-item >确定</van-tabbar-item>
          <van-tabbar-item >取消</van-tabbar-item>
        </van-tabbar>
      </div>
    </van-popup> -->
  </div>
</template>

<script>
import Vue from "vue";
import {
  Popover,
  Skeleton,
  Search,
  List,
  Cell,
  PullRefresh,
  Toast,
  Tabbar,
  TabbarItem,
  Popup,
  DatetimePicker,
  ActionSheet,
  Tab,
  Tabs,
  Collapse,
  CollapseItem,
  Dialog,
  Uploader,
  Rate,
  Icon,
  Form,
  Sticky,
  Image,
  Loading,
  Step,
  Steps,
  NoticeBar,
  Swipe,
  SwipeItem,
} from "vant";
import qs from "qs";
import wx from "weixin-js-sdk";
import * as dd from "dingtalk-jsapi";
import { lazyAMapApiLoaderInstance } from "vue-amap";
import vViews from "@/components/preview/vViews.vue";
import dynamic from "@/components/Dynamic.vue";
import scenario from "@/components/scenario/Scenario.vue";
import tag from "@/components/Tag.vue";
import mytimeline from "@/utils/usetimeline";
import { labelBaseMonthMixins } from '@/mixins/labelBaseMonth.js'
import YYEsnBridge from "@/assets/js/esn.min.js";
import * as df from "@/assets/js/project/default.js";
import headcom from "@/components/scenario/pageHead.vue";
import CustomerTagNotice from "@/components/CustomerTagNotice";
import { eventCommonMixins } from "@/mixins/eventCommon.js";

Vue.use(Popover)
  .use(Skeleton)
  .use(Search)
  .use(List)
  .use(Cell)
  .use(PullRefresh)
  .use(Toast)
  .use(Tabbar)
  .use(TabbarItem)
  .use(Popup)
  .use(DatetimePicker)
  .use(ActionSheet)
  .use(Tab)
  .use(Tabs)
  .use(Collapse)
  .use(CollapseItem)
  .use(Dialog)
  .use(Uploader)
  .use(Rate)
  .use(Icon)
  .use(Form)
  .use(Sticky)
  .use(Image)
  .use(Loading)
  .use(Step)
  .use(Steps)
  .use(NoticeBar)
  .use(Swipe)
  .use(SwipeItem);
export default {
  name: "card",
  components: {
    vViews,
    dynamic,
    tag,
    scenario,
    headcom,
    "customer-tag-notice": CustomerTagNotice,
  },
  mixins: [eventCommonMixins, labelBaseMonthMixins],
  data() {
    return {
      isExpanded: false,
      idobject: this.$route.query.idobject,
      idtemplate: this.$route.query.idtemplate,
      fromobject: this.$route.query.fromobject,
      fromcardid: this.$route.query.fromcardid,
      isrel: this.$route.query.isrel,
      cardid: this.$route.query.itemid,
      isqd: this.$route.query.isqd, // 是否签到
      comePage: this.$route.query.comePage
        ? this.$route.query.comePage
        : "list",
      jsondata: {},
      notice: "",
      bfpjdata: {},
      index: 0,
      active: 0,
      active1: 0,
      activeNames: 0,
      loading: false,
      finished: false,
      rellist: [],
      startline: 1,
      pagecount: 20,
      relcardshow: false,
      reldata: {},
      relactiveNames: [],
      isDisable: false,
      editfield: {},
      updateshow: false,
      updatemsg: {},
      showReview: false,
      myreview: "",
      toast: "",
      tabpage: "scenario",
      hasDynamic: true, // 初始化不为true则需要加载完重新绘制，比较繁琐
      isreload: this.$store.state.isRestart,
      jykfList: [],
      // 最多显示的按钮
      maxVisibleButtons: 2,
      showMoreActionSheet: false,
      showRelHiddenMenuActionSheet: false,
      showBusinessPopup: false,
      reload: false,
      scenarioKey: "scenario0",

      relBusinessMenusArr: [],
      currentBusinessRel: null,
      currentBusinessComponent: null,
      currentBusinessObject: "",
      currentBusinessName: "",
    };
  },
  watch: {
    tabpage: {
      handler(val) {
        this.relBusinessMenusArr = [];
      },
    },
  },
  computed: {
    relBusinessVisibleMenuButtons() {
      return this.relBusinessMenusArr.slice(0, this.maxVisibleButtons) || [];
    },
    relBusinessHiddenMenuButtons() {
      return (
        (this.relBusinessMenusArr.length > this.maxVisibleButtons &&
          this.relBusinessMenusArr.slice(
            this.maxVisibleButtons,
            this.relBusinessMenusArr.length
          )) ||
        []
      );
    },

    relBusinessHiddenMenuActions() {
      return this.relBusinessHiddenMenuButtons.map((item) => {
        return { name: item.title };
      });
    },

    visibleButtons() {
      return (
        this.jsondata.operation &&
        this.jsondata.operation.slice(0, this.maxVisibleButtons)
      );
    },
    hiddenButtons() {
      let data =
        this.jsondata.operation &&
        this.jsondata.operation.slice(this.maxVisibleButtons).filter((item) => {
          item.name = item.title;
          return true;
        });
      //console.log('data', data)
      return data;
    },
  },
  created: function () {
    // this.fetchData()
    //console.log('created......')
    // this.fetchData()
    let _this = this;
    document.title = this.$route.query.stitle;

    // console.log('card', document.title)
    if (dd.env.platform !== "notInDingTalk") {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$route.query.stitle,
        });
      });
    }
  },
  activated: function () {
    //console.log('activated activated activated activated activated', this.reload)
    if (this.reload) {
      this.scenarioKey += 1;
    }
    this.reload = true;
    this.fetchData();
  },
  methods: {
    toggleExpand() {
      this.isExpanded = !this.isExpanded; // 切换展开/收起状态
    },
    handleMenusClick(button) {
      this.handleBusinessOperations(button.title);
    },

    handleMenusSelect(action) {
      this.handleBusinessOperations(action.name);
    },
    handleBusinessCancle() {
      this.showBusinessPopup = false;
    },
    handleBusinesSubmit() {
      this.showBusinessPopup = false;
      this.startline = 1;
      this.onLoad(this.currentBusinessRel, "refresh");
    },
    async handleBusinessOperations(businessName) {
      let module;
      switch (businessName) {
        case "选择发票":
          module = await import(
            "@/components/businessComponents/uploadInvoice"
          );

          break;

        case "上传协议":
          module = await import(
            "@/components/businessComponents/uploadAgreement"
          );

          break;
      }
      this.currentBusinessComponent = module.default;
      this.currentBusinessName = businessName;
      this.showBusinessPopup = true;
    },

    iconClick(tips) {
      // 处理图标点击事件的逻辑
      //console.log('Icon clicked!')
      Toast({
        message: tips,
        position: "top",
      });
    },

    onSelect(action) {
      this.showActionSheet = false;
      // 处理选中的操作，例如跳转到相应页面
      //console.log('选中:', action.name)
      this.excuteFunc(action);
    },

    showFile(item, type) {
      if (!item) {
        Toast("没有找到文件!");
        return;
      }
      //console.log('item', item)
      let fileName = item.file.name;
      let fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
      //console.log(fileExtension)

      //console.log('....type', fileExtension)
      this.$nextTick(() => {
        //console.log('....type', fileExtension)
        //console.log('item.', item)
        //console.log(this.$refs)
        if (type === "1") {
          this.$refs.vViews1.isShow = true;
          this.$refs.vViews1.type = fileExtension;
          this.$refs.vViews1.originSrc = item.url;
          this.$refs.vViews1.showFile(item.url);
        }
        if (type === "2") {
          this.$refs.vViews2.isShow = true;
          this.$refs.vViews2.type = fileExtension;
          this.$refs.vViews2.originSrc = item.url;
          this.$refs.vViews2.showFile(item.url);
        }
      });
    },

    fetchData() {
      let data = {
        [this.idobject + "_id"]: this.cardid,
        [this.idobject + "_idtemplate"]: this.idtemplate,
        fromobject: this.fromobject,
        fromcardid: this.fromcardid,
      };
      //console.log(data)
      this.axios({
        method: "post",
        url: "/api/" + this.idobject + ".check.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          //console.log('res', res)
          if (res.data.editfield) {
            this.editfield = res.data.editfield;
          }

          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            this.jsondata = res.data.jsondata;
            this.handleTagDisplayRes();

            //console.log('jsondata: ', this.jsondata)
            this.hasDynamic = this.jsondata.hasdynamic === 1;
            if (this.jsondata.jykfMap) {
              this.jykfMap = this.jsondata.jykfMap;
              this.jykfMap.id = this.cardid;
              this.jykfMap.obj = this.idobject;
            }

            if (res.data.jsondata.confirmmsg) {
              this.notice = res.data.jsondata.confirmmsg;
              //console.log('==============================')
              //console.log(this.notice.contents)
            }
            // 设置operation的判断
            if (this.$route.query.idobject == "currentstock") {
              this.jsondata.operation = [];
            } else if (
              [
                "dailyreports",
                "weekreports",
                "monthreport1",
                "yzlh2",
                "pxjlb",
                "activity",
                "activitycust",
                "activitybiz",
              ].indexOf(this.$route.query.idobject) >= 0
            ) {
              this.jsondata.operation.push({
                title: "点评",
                mobileFunc: "review",
              });
            } else if (this.$route.query.idobject === "dailyreports") {
              this.jsondata.operation.push({
                title: "轨迹",
                mobileFunc: "showPath",
              });
            }
            if (this.idobject === "xlycbmx") {
              this.jsondata.Details.forEach((i) => {
                i.groupvalue.forEach((iv) => {
                  iv.sTitle = this.replaceNWithMonth(
                    iv.sTitle,
                    Number(this.$route.query.month)
                  );
                });
              });
            }
          }
          if (this.idobject === "activity") {
            let dbegin = "";
            let dend = "";
            let jssj = "";
            let bfxj = "";
            let picture = "";
            let state = {};
            for (let i = 0; i < this.jsondata.Details.length; i++) {
              for (
                let j = 0;
                j < this.jsondata.Details[i].groupvalue.length;
                j++
              ) {
                if (this.jsondata.Details[i].groupvalue[j].sField === "jssj") {
                  jssj = this.jsondata.Details[i].groupvalue[j].value;
                } else if (
                  this.jsondata.Details[i].groupvalue[j].sField === "dbegin"
                ) {
                  dbegin = this.jsondata.Details[i].groupvalue[j].value;
                } else if (
                  this.jsondata.Details[i].groupvalue[j].sField === "dend"
                ) {
                  dend = this.jsondata.Details[i].groupvalue[j].value;
                } else if (
                  this.jsondata.Details[i].groupvalue[j].sField === "state"
                ) {
                  state = this.jsondata.Details[i].groupvalue[j];
                } else if (
                  this.jsondata.Details[i].groupvalue[j].sField === "bfxj"
                ) {
                  bfxj = this.jsondata.Details[i].groupvalue[j].value;
                } else if (
                  this.jsondata.Details[i].groupvalue[j].sField === "picture"
                ) {
                  picture = this.jsondata.Details[i].groupvalue[j].value;
                }
              }
            }
            //console.log(dbegin, dend, jssj, bfxj, picture)
            // //console.log('state:' + JSON.stringify(state))
            // if (dend !== '') {
            //   state.value = '<span style="color:green">已完成<span>'
            // }
            // if (dbegin === undefined || dbegin === '') {
            //   //console.log(this.currenttime() + '>=' + jssj + (this.currenttime() >= jssj))
            //   if (this.currenttime() <= jssj) {
            //     state.value = '<span style="color:#ea9518">待拜访<span>'
            //   } else {
            //     state.value = '<span style="color:red">已超期<span>'
            //   }
            // } else {
            //   if (dend === undefined || dend === '') {
            //     state.value = '<span style="color:blue">拜访中<span>'
            //   }
            // }

            if (state.value === "待拜访") {
              state.value = '<span style="color:#FF7F00">待拜访<span>';
            }

            if (state.value === "签到完成") {
              state.value = '<span style="color:#FAC858">签到完成<span>';
            }

            if (state.value === "已完成") {
              state.value = '<span style="color:#00CD00">已完成<span>';
            }
          }
        })
        .catch((res) => {
          this.reserror(res);
        });
    },
    back(item,object) {
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }
      if (!this.isDisable) {
        this.isDisable = true
        const idobject = this.$route.query.idobject
        let data = { [`${idobject}_id`]: this.cardid }
        this.axios({
          method: 'post',
          url: "/api/" + idobject + "." + item + ".do",
          data: qs.stringify(data)
        }).then((res) => {
          this.loading = false;
          this.showMoreActionSheet = false;
          this.isDisable = false;
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            if (res.data.des.indexOf("成功") > 0) {
              if (
                this.$route.query.fromobject &&
                this.$route.query.fromcardid
              ) {
                this.$router.push({
                  name: "card",
                  query: {
                    idobject: this.$route.query.fromobject,
                    itemid: this.$route.query.fromcardid,
                  },
                });
              } else {
                this.$router.push({
                  name: "list",
                  query: { idobject: realObj },
                });
              }
            }
          }
        })
          .catch((res) => {
            this.loading = false;
            this.isDisable = false;
            this.showMoreActionSheet = false;
            this.reserror(res);
          });
      }
    },
    saveReview() {
      //console.log('itemid:   ' + this.$route.query.itemid)
      // if (this.myreview == '') {
      //   Dialog.confirm({
      //     title: '当前输入内容为空',
      //     message: '确认提交吗？',
      //     confirmButtonColor: 'black',
      //     cancelButtonColor: '#1989fa'
      //   }).then(() => {
      //     // 保存
      //     this.saveDp()
      //   }).catch(() => {
      //     // 点击取消
      //   })
      // } else {
      //   this.saveDp()
      // }
      if (this.myreview === "") {
        Toast("请输入内容后提交");
      } else {
        this.saveDp();
        this.showReview = false;
      }
    },

    saveDp() {
      let _ybbh = "";
      let _zbbh = "";
      let _rbbh = "";
      let _campaignid = "";
      let _activityid = "";
      let _pxjlbid = "";
      let _yzlh2id = "";
      if (this.idobject === "dailyreports") {
        _rbbh = this.$route.query.itemid;
      } else if (this.idobject === "weekreports") {
        _zbbh = this.$route.query.itemid;
      } else if (this.idobject === "monthreport1") {
        _ybbh = this.$route.query.itemid;
      } else if (this.idobject === "campaign") {
        _campaignid = this.$route.query.itemid;
      } else if (
        ["activity", "activitybiz", "activitycust"].includes(this.idobject)
      ) {
        _activityid = this.$route.query.itemid;
      } else if (this.idobject === "pxjlb") {
        _pxjlbid = this.$route.query.itemid;
      } else if (this.idobject === "yzlh2") {
        _yzlh2id = this.$route.query.itemid;
      }

      let data = {
        dpsj: this.currenttime(),
        dpnr: this.myreview,
        ybbh: _ybbh,
        zbbh: _zbbh,
        rbbh: _rbbh,
        campaignid: _campaignid,
        activityid: _activityid,
        pxjlbid: _pxjlbid,
        yzlh2id: _yzlh2id,
      };
      let that = this;
      this.axios({
        method: "post",
        url: "/api/dp.newsave.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.isDisable = false;
          if (res.data.flag === "1") {

            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          }
          //console.log(res)
        })
        .catch((res) => {
          this.isDisable = false;
          //console.log(res)
        });
    },
    currenttime() {
      let d = new Date();
      let year = d.getFullYear();
      let month = this.change(d.getMonth() + 1);
      let day = this.change(d.getDate());
      let hour = this.change(d.getHours());
      let minute = this.change(d.getMinutes());
      let second = this.change(d.getSeconds());
      let time =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        ":" +
        minute +
        ":" +
        second;
      return time;
    },

    cancelReview() {
      this.showReview = false;
      this.isDisable = false;
    },

    auditEdit(fieldvalue) {
      // Toast('auditEdit')
      this.updateshow = true;
      this.updatemsg.id = fieldvalue.ID;
      //console.log(this.updatemsg)
      fieldvalue.updatevalue = fieldvalue.value;
    },

    auditEditSave(fieldvalue) {
      // Toast('auditEditSave')
      this.updateshow = false;
      this.updatemsg.id = "";
      //console.log(this.updatemsg)
      fieldvalue.value = fieldvalue.updatevalue;
      this.axios({
        methods: "post",
        url: "/api/" + this.idobject + ".updatefieldsave.do",
        data: "",
      })
        .then((res) => {
          // Toast(res.data.jsondata.success)
          //console.log(res)
        })
        .catch((res) => {
          this.reserror(res);
        });
    },

    auditEditCancel(fieldvalue) {
      //console.log('auditEditCancel...')
      this.updateshow = false;
      this.updatemsg.id = "";
    },

    isEditField(fieldvalue) {
      //console.log('isEditField...')
      let editArr = this.editfield.data;
      for (const i in editArr) {
        if (Object.hasOwnProperty.call(editArr, i)) {
          const element = editArr[i];
          if (element.sfield === fieldvalue.sField) {
            fieldvalue.beforevalue = fieldvalue.value;
            return true;
          }
        }
      }
      return false;
    },

    handlePopoverButtonClick(button) {
      button.action();
      this.showPopover = false;
    },

    excuteFunc(item) {
      if (!this.isDisable) {
        // this.isDisable = true;
        //console.log(item.mobileFunc)
        if (item.mobileFunc === "edit") {
          this.edit();
        } else if (item.mobileFunc === "review") {
          this.review();
        } else if (item.mobileFunc === "submit" || item.mobileFunc === "flowsubmit") {
          this.submit();
        } else if (item.mobileFunc === "flowback") {
          this.back(item.mobileFunc);
        } else if (item.mobileFunc === "del") {
          this.del();
        } else if (item.mobileFunc === "rk") {
          this.rk();
        } else if (item.mobileFunc === "audit") {
          this.audit();
        } else if (item.mobileFunc === "unaudit") {
          this.unaudit();
        } else if (item.mobileFunc === "htxz") {
          //console.log('下载')
          //console.log(window.location.origin)
          //console.log(this.jsondata.operation[0])
          let op = this.jsondata.operation[0];
          // window.location = "http://60.211.225.210:7179/tosignserver/api/document/last/1438385643410448384?_app_id=e044ada0fc524e859a368b0af9ac15a9";
          this.axios({
            method: "get",
            url:
              "/api/" +
              op.object +
              ".htxz.do?id=" +
              this.cardid +
              "&ip=" +
              window.location.origin,
          })
            .then((res) => {
              this.isDisable = false;
              let errmsg = res.data.errmsg;
              if (errmsg) {
                Toast(errmsg);
                throw errmsg;
              }

              //console.log(res.data.downurl)
              if (res.data.downurl) {
                // window.open(downurl)
                // window.location = res.data.downurl;
                const ele = document.createElement("a");
                ele.setAttribute("href", res.data.downurl); // 设置下载文件的url地址
                let str = res.data.downurl.substring(
                  res.data.downurl.lastIndexOf("/")
                );
                let str2 = str.split("/")[1];
                ele.setAttribute("download", str2); // 用于设置下载文件的文件名
                ele.click();
              }
            })
            .catch((res) => {
              this.isDisable = false;
              this.reserror(res);
            });
          // Toast('开始下载')
        } else if (item.mobileFunc === "fuhe") {
          this.axios({
            method: "get",
            url: "/api/" + this.idobject + ".fuhe.do?id=" + this.cardid,
          })
            .then((res) => {
              //console.log(res)
              if (res.data.flag === 0) {
                Toast("复核成功");
              }
              if (res.data.flag === 1) {
                Toast(res.data.des);
                if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
                  this.loginout();
                }
              }

              this.isDisable = false;
            })
            .catch((res) => {
              this.reserror(res);
              this.isDisable = false;
            });
        } else if (item.mobileFunc === "bfjl") {
          // 拜访记录
          this.$router.push({
            name: "activitybfjl",
            query: {
              itemid: this.cardid,
              idobject: this.idobject,
              fromobject: this.fromobject,
              idtemplate: this.idtemplate,
            },
          });
          this.isDisable = false;
        } else if (item.mobileFunc === "activityqian") {
          // this.$router.push({ name: 'activityqian', query: { itemid: this.cardid, idobject: this.idobject } })
          this.isDisable = false;
          this.checkin();
        } else if (item.mobileFunc === "renew") {
          //console.log('renew...')
          if (!this.exitIfNotAudited()) return;
          this.$router.push({
            name: "renew",
            query: {
              func: "renew",
              itemid: this.cardid,
              idobject: this.idobject,
              fromobject: this.fromobject,
              idtemplate: this.idtemplate,
            },
          });
          this.isDisable = false;
        } else if (item.mobileFunc === "newversion") {
          //console.log('newversion...')
          if (!this.exitIfNotAudited()) return;
          //console.log('continue...')
          this.$router.push({
            name: "newversion",
            query: {
              func: "newversion",
              itemid: this.cardid,
              idobject: this.idobject,
              fromobject: this.fromobject,
              idtemplate: this.idtemplate,
            },
          });
          this.isDisable = false;
        } else if (item.mobileFunc === "contract") {
          //console.log('contract...')
          this.contract();
        } else if (item.mobileFunc === "htfq") {
          //console.log('htfq...')
          this.htfq();
        } else if (item.mobileFunc === "htsign") {
          //console.log('htsign...')
          this.htsign();
        } else if (item.mobileFunc === "close") {
          //console.log('close...')
        } else if (item.mobileFunc === "fphx") {
          //console.log('fhpx...')
          this.fphx();
        } else if (item.mobileFunc === "hyysbx") {
          df.xshybx(this, "hyysbx");
        } else if (item.mobileFunc === "hyjzbx") {
          df.xshybx(this, "hyjzbx");
        }
        //   this.axios({
        //     method: 'get',
        //     url: '/api/' + this.idobject + '.fuhe.do?id=' + this.cardid
        //   }).then(res => {
        //     //console.log(res)
        //     if (res.data.flag === 0) {
        //       Toast('复核成功')
        //     }
        //     if (res.data.flag === 1) {
        //       Toast(res.data.des)
        //     }
        //
        //     this.isDisable = false
        //   }).catch(res => {
        //     this.reserror(res)
        //     this.isDisable = false
        //   })
        // }
      }
    },

    exitIfNotAudited() {
      let canDo = true;
      // 操作中有审核按钮 就表示没有审核
      this.jsondata.operation.some((i) => {
        if (i.title === "审核") {
          canDo = false;
          return true;
        }
      });
      //console.log('canDO:', canDo)
      if (!canDo) {
        Toast("请审核后再进行操作!");
        this.isDisable = false;
        return false;
      }
      return true;
    },

    excuteFunc1(item, object) {
      if (!this.isDisable) {
        // this.isDisable = true;
        if (item.mobileFunc === "edit") {
          this.edit(object);
        } else if (item.mobileFunc === "submit") {
          this.submit(object);
        } else if (item.mobileFunc === "del") {
          this.del(object);
        } else if (item.mobileFunc === "audit") {
          this.audit(object);
        } else if (item.mobileFunc === "unaudit") {
          this.unaudit(object);
        }
      }
    },

    showPath() {
      let data = { itemid: this.cardid, idobject: this.idobject };
      this.axios({
        method: "post",
        url: "/api/" + this.idobject + ".path.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          if (res.data && JSON.parse(res.data.posi).length > 0) {
            //console.log('11111')
            //console.log(res.data)
            this.$router.push({
              name: "mappath",
              query: {
                pathdata: JSON.parse(res.data.posi),
                allinfo: JSON.parse(res.data.allinfo),
              },
            });
          } else {
            Toast("暂无轨迹");
            //console.log(res.data)
          }
        })
        .catch((res) => {
          this.reserror(res);
        });
    },

    targetList(fieldvalue) {
      let targetbo = fieldvalue.snote.substring(
        0,
        fieldvalue.snote.indexOf(".")
      );
      let extract = fieldvalue.snote.substring(
        fieldvalue.snote.indexOf("=") + 1
      );
      this.$router.push({
        name: "list",
        query: { idobject: targetbo, extract: extract },
      });
    },

    edit(object) {
      if (object != null) {
        this.isDisable = false;
        // 说明是选项卡来的
        this.$router.push({
          name: "edit",
          query: {
            stitle: this.$route.query.stitle,
            itemid: this.rellist[0].id,
            idobject: object,
            fromobject: this.idobject,
            fromcardid: this.cardid,
          },
        });
        return;
      }
      /* if (this.idobject === 'activity') {
        this.$router.push({ name: 'activityedit', query: { stitle: this.$route.query.stitle, itemid: this.cardid, idobject: this.idobject } })
      } else {
      } */
      this.$router.push({
        name: "edit",
        query: {
          stitle: this.$route.query.stitle,
          itemid: this.cardid,
          idobject: this.idobject,
          fromobject: this.fromobject,
          fromcardid: this.fromcardid,
        },
      });
    },
    submit(object) {
      this.isDisable = true;
      this.loading = true;
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      let data = { [realObj + "_id"]: realId };
      this.axios({
        method: "post",
        url: "/api/" + realObj + ".flowsubmit.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.loading = false;
          this.showMoreActionSheet = false;
          this.isDisable = false;
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            if (res.data.des.indexOf("成功") > 0) {
              if (
                this.$route.query.fromobject &&
                this.$route.query.fromcardid
              ) {
                this.$router.push({
                  name: "card",
                  query: {
                    idobject: this.$route.query.fromobject,
                    itemid: this.$route.query.fromcardid,
                  },
                });
              } else {
                this.$router.push({
                  name: "list",
                  query: { idobject: realObj },
                });
              }
            }
          }
        })
        .catch((res) => {
          this.loading = false;
          this.isDisable = false;
          this.showMoreActionSheet = false;
          this.reserror(res);
        });
    },

    del(object) {
      this.isDisable = true;
      Dialog.confirm({
        title: "删除",
        message: "确认删除吗？",
      })
        .then(() => {
          // on confirm
          let realObj = "";
          let realId = "";
          if (object != null) {
            realObj = object;
            realId = this.rellist[0].id;
          } else {
            realObj = this.idobject;
            realId = this.cardid;
          }
          let data = { [realObj + "_id"]: realId };

          this.axios({
            method: "post",
            url: "/api/" + realObj + ".del.do",
            data: qs.stringify(data),
          })
            .then((res) => {
              this.isDisable = false;
              if (res.data.flag === "1") {
                Toast(res.data.des);
                if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
                  this.loginout();
                }
              } else {
                Toast("删除成功");
                // 此处应该带着条件刷新列表
                if (
                  this.$route.query.fromobject &&
                  this.$route.query.fromcardid
                ) {
                  this.$router.push({
                    name: "card",
                    query: {
                      idobject: this.$route.query.fromobject,
                      itemid: this.$route.query.fromcardid,
                    },
                  });
                } else {
                  this.$router.push({
                    name: "list",
                    query: { idobject: this.idobject },
                  });
                }
              }
            })
            .catch((res) => {
              this.isDisable = false;
              this.reserror(res);
            });
        })
        .catch(() => {
          // on cancel
          this.isDisable = false;
        });
    },

    onLoad(rel, mode = "push") {
      this.loading = true;
      let data = {
        startline: this.startline,
        pagecount: this.pagecount,
        relfield: rel.relfield,
        relvalue: this.cardid,
        viewoption: rel.view_id,
        relObject: rel.current_toobject,
      };
      let url = "";
      if (rel.current_object === "flowclmx") {
        url = "/api/" + rel.current_object + ".list-rel.do";
      } else {
        url = "/api/" + rel.current_object + ".list.do";
      }
      this.axios({
        method: "post",
        url: url,
        data: qs.stringify(data),
      })
        .then((res) => {
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            this.relBusinessMenusArr = res.data.menus || [];

            let rsdata = res.data.jsondata.fieldValue;

            if (mode === "refresh") {
              this.rellist = [];
            }
            for (let i = 0; i < rsdata.length; i++) {
              this.rellist.push(rsdata[i]);
            }

            this.bfpjdata = {};
            if (
              this.rellist.length > 0 &&
              (this.rellist[0].bfpj_id !== undefined ||
                this.rellist[0].hdpj_id !== undefined)
            ) {
              this.checkBfpj(this.rellist[0]);
            }

            if (
              rsdata == null ||
              rsdata.length === 0 ||
              rsdata.length < this.pagecount
            ) {
              this.loading = false;
              this.finished = true;
            } else {
              this.startline = this.startline + rsdata.length;
              this.loading = false;
            }
          }
        })
        .catch((res) => {
          this.reserror(res);
        });
    },

    openRel(name, title) {
      this.rellist = [];
      this.startline = 1;

      for (let i = 0; i < this.jsondata.relevant.length; i++) {
        let rel = this.jsondata.relevant[i];

        if (name === rel.ui_key) {
          this.currentBusinessRel = rel;
          this.currentBusinessObject = rel.current_object;
          this.onLoad(rel);
        }
      }
    },

    addRel(rel) {
      if (rel.current_object === "qiandao") {
        this.$router.push({
          name: "qiandaonew",
          query: {
            idobject: rel.current_object,
            idtemplate: this.idtemplate,
            fromobject: this.idobject,
            fromcardid: this.cardid,
          },
        });
      } else {
        this.$router.push({
          name: "relnew",
          query: {
            relfield: rel.relfield,
            relvalue: this.cardid,
            relobject: rel.current_object,
            idobject: this.idobject,
            fromcardid: this.cardid,
          },
        });
      }
    },

    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },

    rk() {
      this.$router.push({
        name: "new",
        query: { idobject: "skd", skdtid: this.cardid, operation: "rk" },
      });
    },

    audit(object) {
      this.isDisable = true;
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }
      let data = { [realObj + "_id"]: realId };

      this.axios({
        method: "post",
        url: "/api/" + realObj + ".audit.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.isDisable = false;
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            if (res.data.des.indexOf("成功") > 0) {
              if (
                this.$route.query.fromobject &&
                this.$route.query.fromcardid
              ) {
                this.$router.push({
                  name: "card",
                  query: {
                    idobject: this.$route.query.fromobject,
                    itemid: this.$route.query.fromcardid,
                  },
                });
              } else {
                this.$router.push({
                  name: "list",
                  query: {
                    idobject: this.idobject,
                    stitle: this.$route.query.stitle,
                  },
                });
              }
            }
          }
        })
        .catch((res) => {
          this.isDisable = false;
          this.reserror(res);
        });
    },

    unaudit(object) {
      this.isDisable = true;
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      let data = { [realObj + "_id"]: realId };

      this.axios({
        method: "post",
        url: "/api/" + realObj + ".unaudit.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.isDisable = false;
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            if (res.data.des.indexOf("成功") > 0) {
              if (
                this.$route.query.fromobject &&
                this.$route.query.fromcardid
              ) {
                this.$router.push({
                  name: "card",
                  query: {
                    idobject: this.$route.query.fromobject,
                    itemid: this.$route.query.fromcardid,
                  },
                });
              } else {
                this.$router.push({
                  name: "list",
                  query: {
                    idobject: this.idobject,
                    stitle: this.$route.query.stitle,
                  },
                });
              }
            }
          }
        })
        .catch((res) => {
          this.isDisable = false;
          this.reserror(res);
        });
    },

    openRelCard(rel, item) {
      console.log(
        "openRelCard",
        this.comePage,
        rel,
        item,
        this.cardid,
        this.fromcardid
      );
      let month;
      for (let groupindex in this.jsondata.Details) {
        let itemgroup = this.jsondata.Details[groupindex].groupvalue;
        for (let itemindex in itemgroup) {
          let itemdata = itemgroup[itemindex];
          if (itemdata.sField === "yf") {
            month = itemdata.value.split(">")[1].split("<")[0].split("-")[1];
            month = parseInt(month, 10) < 10 ? month.replace(/^0+/, "") : month;
          }
        }
      }
      if (this.comePage == "list") {
        this.$router.push({
          name: "card",
          query: {
            stitle: rel.title,
            comePage: "card",
            VNK: "card" + new Date().getTime(),
            itemid: item.id,
            idobject: rel.current_object,
            fromobject: this.idobject,
            fromcardid: this.cardid,
            isrel: true,
            month,
          },
        });
      } else {
        this.$router.replace({
          name: "card",
          query: {
            stitle: rel.title,
            comePage: "card",
            VNK: "card" + new Date().getTime(),
            itemid: item.id,
            idobject: rel.current_object,
            fromobject: this.idobject,
            fromcardid: this.cardid,
            isrel: true,
          },
        });
      }
    },

    checkBfpj(showdata) {
      //console.log('checkBfpj', showdata)
      let objectid = "";
      let object = "";
      if (showdata.hdpj_id !== undefined) {
        objectid = showdata.hdpj_id;
        object = "hdpj";
      } else if (showdata.bfpj_id !== undefined) {
        objectid = showdata.bfpj_id;
        object = "bfpj";
      }
      let data = { [object + "_id"]: objectid };
      this.axios({
        method: "post",
        url: "/api/" + object + ".check.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            this.bfpjdata = res.data.jsondata;
            //console.log('bfpjdata')
            //console.log(this.bfpjdata)
          }
        })
        .catch((res) => {
          this.reserror(res);
        });
    },

    review() {
      //console.log('review')
      //console.log('this.showReview', this.showReview)
      this.showReview = true;
      //console.log('showReview', this.showReview)
      // this.showReview = false
      // if (rel) {
      //   this.$router.push({ name: 'relnew',
      //     query: {
      //       'relfield': rel.relfield,
      //       'relvalue': this.cardid,
      //       'relobject': rel.current_object,
      //       'idobject': this.idobject
      //     }
      //   })
      // }
    },
    // 点击签到按钮 不弹出界面
    checkin() {
      this.getlocation("begin");
    },

    save() {
      if (!this.isDisable) {
        let cansave = 1;
        this.overlayShow = true;
        this.isDisable = true;
        let data = {};
        data[this.idobject + "_id"] = this.cardid;
        for (let groupindex in this.jsondata.head) {
          let itemgroup = this.jsondata.head[groupindex].groupvalue;
          for (let itemindex in itemgroup) {
            let itemdata = itemgroup[itemindex];
            if (itemdata.sUIType === "ref") {
              data[itemdata.idObject + "_" + itemdata.sField] =
                itemdata.valuehidden;
              data[itemdata.idObject + "_" + itemdata.sField + "_ref"] =
                itemdata.value;
            } else if (itemdata.sUIType === "enum") {
              data[itemdata.idObject + "_" + itemdata.sField] =
                itemdata.valuehidden;
              data[itemdata.idObject + "_" + itemdata.sField + "_enum"] =
                itemdata.value;
            } else if (
              itemdata.sUIType === "file" ||
              itemdata.sUIType === "picture"
            ) {
              data[itemdata.idObject + "_" + itemdata.sField] =
                itemdata.valuehidden;
              data[itemdata.idObject + "_" + itemdata.sField + "_title"] =
                itemdata.value;
            } else {
              data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
            }
            if (itemdata.lMustInput === "1" && itemdata.value === "") {
              itemdata.errormsg = "不能为空";
              cansave = 0;
            }
          }
        }
        if (cansave === 0) {
          this.isDisable = false;
          this.overlayShow = false;
          return;
        }

        this.axios({
          method: "post",
          url: "/api/" + this.idobject + ".editsave.do",
          data: qs.stringify(data),
        })
          .then((res) => {
            this.isDisable = false;
            this.overlayShow = false;
            if (res.data.flag === "0") {
              this.submittedByButton = true;
              // this.$router.push({ name: 'card', query: { itemid: this.$route.query.itemid, idobject: this.idobject } })
              this.$router.go(-1);
              // this.$router.push({ name: 'list', query: { idobject: this.idobject } })
              // this.$router.push({ name: 'bizcalendar' })
            } else {
              Toast(res.data.des);
              if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
                this.loginout();
              }
            }
            //console.log(res)
          })
          .catch((res) => {
            this.isDisable = false;
            this.overlayShow = false;
            //console.log(res)
          });
      }
    },

    saveTimeAndAddress(bs) {
      // alert(JSON.stringify(data))
      let data = {};
      let baddress = "";
      let jd = "";
      let wd = "";
      let distanceItem = {};
      let beginItem = {};
      let endItem = {};
      let _this1 = this;
      data[this.idobject + "_id"] = this.cardid;
      data["hasstarted"] = this.hasstarted;
      data["hasdeparted"] = this.hasdeparted;
      for (let groupindex in this.jsondata.Details) {
        let itemgroup = this.jsondata.Details[groupindex].groupvalue;
        for (let itemindex in itemgroup) {
          let itemdata = itemgroup[itemindex];
          if (itemdata.sField === "baddress") {
            baddress = itemdata.value;

            beginItem = itemdata;
          }
          if (itemdata.sField === "eaddress") {
            endItem = itemdata;
          }
          if (itemdata.sField === "idaccount") {
            jd = itemdata.jd;
            wd = itemdata.wd;
          }
          if (itemdata.sField === "distance") {
            distanceItem = itemdata;
          }
          if (itemdata.sUIType === "ref") {
            data[itemdata.idObject + "_" + itemdata.sField] =
              itemdata.valuehidden;
            data[itemdata.idObject + "_" + itemdata.sField + "_ref"] =
              itemdata.value;
          } else if (itemdata.sUIType === "enum") {
            data[itemdata.idObject + "_" + itemdata.sField] =
              itemdata.valuehidden;
            data[itemdata.idObject + "_" + itemdata.sField + "_enum"] =
              itemdata.value;
          } else if (
            itemdata.sUIType === "file" ||
            itemdata.sUIType === "picture"
          ) {
            data[itemdata.idObject + "_" + itemdata.sField] =
              itemdata.valuehidden;
            data[itemdata.idObject + "_" + itemdata.sField + "_title"] =
              itemdata.value;
          } else {
            data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
          }
        }
      }
      var geocoder = new AMap.Geocoder({});

      let lnglat = [];
      let objectfield = "";
      if (bs === "end") {
        objectfield = this.idobject + "_eaddress";
        lnglat = data[objectfield].split(",");
      } else {
        objectfield = this.idobject + "_baddress";
        if (data[objectfield].indexOf("&") >= 0) {
          data[objectfield] = data[objectfield].substring(
            data[objectfield].indexOf("&") + 1
          );
        }
        lnglat = data[objectfield].split(",");

        if (jd && wd) {
          lazyAMapApiLoaderInstance.load().then(() => {
            AMap.plugin("AMap.Geocoder", function () {
              var lnglat = [
                Number(baddress.split(",")[0]),
                Number(baddress.split(",")[1]),
              ];
              var p2 = [Number(jd), Number(wd)];
              var distance = AMap.GeometryUtil.distance(lnglat, p2);
              distanceItem.value = Math.round(distance);
              data["activity_distance"] = distanceItem.value;
            });
          });
        }
      }
      geocoder.getAddress(lnglat, function (status, result) {
        var address = "";
        // //console.log('地图status:' + status)
        // //console.log('地图result' + JSON.stringify(result))
        if (status === "complete" && result.regeocode) {
          address = result.regeocode.formattedAddress;
        } else {
          Toast("根据经纬度获取地址失败");
        }

        data[objectfield] = address + "&" + data[objectfield];

        if (bs === "end") {
          endItem.value = data[objectfield];
        } else {
          beginItem.value = data[objectfield];
        }
        _this1
          .axios({
            method: "post",
            url: "/api/" + _this1.idobject + ".begin.do",
            data: qs.stringify(data),
          })
          .then((res) => {
            _this1.isDisable = false;
            _this1.overlayShow = false;
            if (res.data.flag === "0") {
              _this1.toast.clear();
              _this1.fetchData();
              Toast("签到成功!");
            } else {
              Toast(res.data.des);
              if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
                this.loginout();
              }
            }
            //console.log(res)
          })
          .catch((res) => {
            this.isDisable = false;
            this.overlayShow = false;
            //console.log(res)
            Toast("请求失败" + res);
          });
      });
    },

    getlocation(type1) {
      this.toast = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "签到中...请稍候",
      });
      let ua = window.navigator.userAgent.toLowerCase();
      //console.log(ua)
      let logintype = "wechat";
      let tourl = window.location.href;
      let clttype = "android";
      if (ua.indexOf("iphone") !== -1) {
        clttype = "ios";
      }
      if (ua.indexOf("wxwork") !== -1) {
        logintype = "wxwork";
      } else if (ua.indexOf("dingtalk") !== -1) {
        logintype = "dingding";
        tourl =
          window.location.protocol +
          "//" +
          window.location.host +
          "/vue-common/dist/main";
      } else if (ua.indexOf("micromessenger") !== -1) {
        logintype = "wechat";
      } else if (ua.indexOf("tenantid") !== -1) {
        // 友空间
        logintype = "ykj";
      } else {
        logintype = "browser";
      }
      if (logintype === "browser") {
        alert("请在钉钉或微信端登录!");
        this.toast.clear();
        this.$router.go(-1);
      }
      let _this = this;
      let data = {
        url: tourl,
        type: logintype,
        clttype: clttype,
      };

      let url = "/api/" + this.idobject + ".getlocation.do";

      this.axios({
        method: "post",
        url: url,
        data: qs.stringify(data),
      })
        .then((res) => {
          if (
            res.data.flag === "1" &&
            res.data.des &&
            res.data.des.indexOf("登录过期") >= 0
          ) {
            Toast(res.data.des);
            this.loginout();
          } else {
            let data = res.data;
            if (logintype === "wechat" || logintype === "wxwork") {
              wx.config({
                beta: true,
                debug: false,
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: [
                  "chooseImage",
                  "previewImage",
                  "uploadImage",
                  "downloadImage",
                  "previewFile",
                  "getLocation",
                ],
              });
              wx.ready(function () {
                wx.getLocation({
                  isHighAccuracy: true,
                  type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                  success: function (res) {
                    var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    for (let groupindex in _this.jsondata.Details) {
                      for (let itemindex in _this.jsondata.Details[groupindex]
                        .groupvalue) {
                        let item =
                          _this.jsondata.Details[groupindex].groupvalue[
                          itemindex
                          ];

                        if (type1 === "begin") {
                          if (item.sField === "baddress") {
                            item.value = longitude + "," + latitude;
                          }
                          if (item.sField === "dbegin") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                        } else if (type1 === "end") {
                          if (item.sField === "dend") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                          if (item.sField === "eaddress") {
                            item.value = longitude + "," + latitude;
                          }
                        }
                      }
                    }

                    _this.saveTimeAndAddress(type1);
                    _this.toast.clear();
                  },
                  fail: function (err) {
                    alert("请检查定位是否已经打开!");
                    //console.log(JSON.stringify(err))
                    _this.toast.clear();
                  },
                });
              });
            } else if (logintype === "dingding") {
              dd.config({
                agentId: data.agentid,
                corpId: data.appId,
                timeStamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                type: 0,
                jsApiList: [
                  "runtime.info",
                  "biz.contact.choose",
                  "device.notification.confirm",
                  "device.notification.alert",
                  "device.notification.prompt",
                  "biz.ding.post",
                  "biz.util.openLink",
                  "device.geolocation.get",
                ],
              });
              dd.ready(function () {
                dd.device.geolocation.get({
                  targetAccuracy: 200,
                  coordinate: 1,
                  withReGeocode: false,
                  useCache: true,
                  onSuccess: function (result) {
                    var longitude = result.longitude;
                    var latitude = result.latitude;
                    for (let groupindex in _this.jsondata.Details) {
                      for (let itemindex in _this.jsondata.Details[groupindex]
                        .groupvalue) {
                        let item =
                          _this.jsondata.Details[groupindex].groupvalue[
                          itemindex
                          ];
                        if (type1 === "begin") {
                          if (item.sField === "baddress") {
                            item.value = longitude + "," + latitude;
                          }
                          if (item.sField === "dbegin") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                        } else if (type1 === "end") {
                          if (item.sField === "dend") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                          if (item.sField === "eaddress") {
                            item.value = longitude + "," + latitude;
                          }
                        }
                      }
                    }
                    _this.toast.clear();
                    _this.saveTimeAndAddress(type1);
                  },
                  onfail: function (err) {
                    _this.toast.clear();
                    //console.log(JSON.stringify(err))
                    alert("请检查定位是否已经打开!");
                  },
                });
              });
              dd.error(function (error) {
                alert("dd error: " + JSON.stringify(error));
              });
            } else if (logintype === "ykj") {
              YYEsnBridge.ready(function () {
                YYEsnBridge.do("getLocationInfo", {
                  agentId: data.agentid,
                  timeStamp: data.timestamp,
                  signature: data.signature,
                  success: function (res) {
                    let longitude = res.longitude;
                    let latitude = res.latitude;
                    for (let groupindex in _this.jsondata.Details) {
                      for (let itemindex in _this.jsondata.Details[groupindex]
                        .groupvalue) {
                        let item =
                          _this.jsondata.Details[groupindex].groupvalue[
                          itemindex
                          ];
                        if (type1 === "begin") {
                          if (item.sField === "baddress") {
                            item.value = longitude + "," + latitude;
                          }
                          if (item.sField === "dbegin") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                        } else if (type1 === "end") {
                          if (item.sField === "dend") {
                            let _currenttime = _this.currenttime();
                            item.value = _currenttime;
                          }
                          if (item.sField === "eaddress") {
                            item.value = longitude + "," + latitude;
                          }
                        }
                      }
                    }
                    _this.toast.clear();
                    _this.saveTimeAndAddress(type1);
                  },
                  fail: function (err) {
                    _this.toast.clear();
                    alert(
                      "调用失败,请检查定位是否已经打开!" + JSON.stringify(err)
                    );
                    //console.log(JSON.stringify(err))
                  },
                  complete: function (res) {
                    // alert('调用完成后执行');
                    //console.log('调用完毕:' + JSON.stringify(res))
                  },
                });
              });
            } else {
              // 不做处理
              _this.toast.clear();
              alert("请在钉钉或微信使用该功能!");
            }
          }
        })
        .catch(function (error) {
          _this.toast.clear();
          alert(error);
        });
    },
    contract(object) {
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      let data = { ui_tokey: realId };
      this.axios({
        method: "post",
        url: "/api/" + realObj + ".savecontract.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.isDisable = false;
          //console.log(res)
          Toast(res.data.des);
          if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
            this.loginout();
          }
          if (res.data.message === "合同生成完成!") {
            Toast(res.data.des + "");
          } else {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          }
        })
        .catch((res) => {
          this.isDisable = false;
          this.reserror(res);
        });
    },
    htfq(object) {
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      let data = { [realObj + "_id"]: realId };
      this.axios({
        method: "post",
        url: "/api/" + realObj + ".htfq.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          //console.log(res)
          this.isDisable = false;
          if (res.data.flag === "1") {
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            //console.log(res.data.des)
            if (res.data.des.indexOf("SUCCESS") !== -1) {
              this.$router.push({ name: "list", query: { idobject: realObj } });
            }
          }
        })
        .catch((res) => {
          this.isDisable = false;
          this.reserror(res);
        });
    },
    htsign(object) {
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      let data = { [realObj + "_id"]: realId };
      this.axios({
        method: "post",
        url: "/api/" + realObj + ".htsign.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          this.isDisable = false;
          if (res.data.flag === "1") {
            //console.log('htsign request fail')
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            Toast(res.data.des + " ");
            //console.log(res.data.des)
            if (res.data.des.indexOf("SUCCESS") !== -1) {
              //console.log('htsign request success')
              //console.log(res.data.signurl)
              window.location.href = res.data.signurl;
            }
          }
        })
        .catch((res) => {
          this.isDisable = false;
          this.reserror(res);
        });
    },
    fphx(object) {
      let realObj = "";
      let realId = "";
      if (object != null) {
        realObj = object;
        realId = this.rellist[0].id;
      } else {
        realObj = this.idobject;
        realId = this.cardid;
      }

      this.$router.push({
        path: "invoicecancel",
        query: {
          realObj,
          realId,
        },
      });
      return;

      let data = { [realObj + "_id"]: realId };
      this.axios({
        method: "post",
        url: "/api/" + realObj + ".fphx.do",
        data: qs.stringify(data),
      })
        .then((res) => {
          //console.log('res:' + JSON.stringify(res))
          this.isDisable = false;
          if (res.data.flag === "1") {
            //console.log('发票核销 request fail')
            Toast(res.data.des);
            if (res.data.des && res.data.des.indexOf("登录过期") >= 0) {
              this.loginout();
            }
          } else {
            // Toast(res.data.des + ' ')
            if (res.data.des.indexOf("SUCCESS") !== -1) {
              //console.log('fphx request success')
              this.$router.push({
                name: "invoicecancel",
                params: {
                  data: res.data.jsondata,
                },
              });
            }
          }
        })
        .catch((res) => {
          //console.log('res:' + res)
          this.isDisable = false;
          this.reserror(res);
        });
    },
  },
};
</script>

<style src="@/assets/css/tags.css"></style>
<style scoped>
/* 展开后的样式 */
.multi-line-notice {
  white-space: pre-line !important;
  /* 关键样式 */
  padding: 8px 16px;
  /* 增加内边距使多行更美观 */
}

:deep(.expanded-notice) {
  height: auto !important;
  /* 解除高度限制 */
  white-space: normal !important;
  /* 允许换行 */
  padding: 10px 15px;
  /* 增加内边距 */
}
</style>
<style>
/*.card .card_top {
    background-color: rgba(78,126,194);
    background-color: rgba(63, 143, 255);
    padding: 5px 0px 3px 15px;
  }*/
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 1px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}

.valueleft {
  min-width: 70%;
  white-space: pre-wrap;
  display: inline-block;
  text-align: left;
  word-break: break-all;
}

.cellvalue1 .van-cell__value {
  position: relative;
  overflow: hidden;
  color: #323233;
  text-align: left;
  vertical-align: middle;
  word-wrap: break-word;
  flex: 2;
}

.cellvalue1 .van-cell__title {
  color: #999;
}

.notice-swipe {
  height: 40px;
  line-height: 40px;
}

.van-swipe-item {
  overflow: hidden;
}
</style>
